﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HRWEB.Models;
using HRWEB.HtmlHelpers;
using System.Linq.Expressions;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;


namespace HRWEB.Controllers
{
    [Authorize(Roles="DeptMaster")]
    public class DeptMasterController : Controller
    {

        hrdbEntities ent = new hrdbEntities();
        public ActionResult Index()
        {
            DeptEmployeeModel m = new DeptEmployeeModel();
            string id = HttpContext.Profile["ID"].ToString();
            if (string.IsNullOrEmpty(id))
            {
                return RedirectToAction("Index", "Home");
            }
            var s_deptCode = from d in ent.TDictDepts where d.FKQShenHe == id select d;
            if (!s_deptCode.Any())
            {
                return RedirectToAction("Index", "Home");
            }
            m.Depts = s_deptCode.ToList();
            m.SelectedDeptCode = s_deptCode.First().FDeptCode;
            m.DispAll = true;
            //Expression<Func<TEmployee, bool>> where = x => x.TDepts.OrderBy(p => p.FValidDate).Last().FKQDeptCode == m.SelectedDeptCode;
            //m.Employees = ent.TEmployees.Where(where.Compile()).ToList();
            //foreach (TEmployee emp in ent.TEmployees)
            //{
            //    if (emp.TDepts.OrderBy(p => p.FValidDate).Last().FKQDeptCode == m.SelectedDeptCode)
            //    {
            //        list.Add(emp);
            //    }
            //}

            //var s1=from e in ent.TEmployees join d in ent.TDepts on e.FEmployeeID equals d.FEmployeeID into ed from kk in ed.DefaultIfEmpty() orderby kk.
            return View(BuildDeptModel(m));
        }
       
        public ActionResult ChangeViewMode(string deptCode,bool dispAll)
        {
            string id = HttpContext.Profile["ID"].ToString();
            DeptEmployeeModel m = new DeptEmployeeModel();
            var s_deptCode = from d in ent.TDictDepts where d.FKQShenHe == id select d;
            m.Depts = s_deptCode.ToList();
            m.SelectedDeptCode = deptCode;
            m.DispAll = dispAll;
            return View("Index", BuildDeptModel(m));
        }
        public ActionResult Export(string deptCode, bool dispAll)
        {
            string id = HttpContext.Profile["ID"].ToString();
            DeptEmployeeModel m = new DeptEmployeeModel();
            var s_deptCode = from d in ent.TDictDepts where d.FKQShenHe == id select d;
            m.Depts = s_deptCode.ToList();
            m.SelectedDeptCode = deptCode;
            m.DispAll = true;
            DeptEmployeeModel m2 = BuildDeptModel(m);
            List<TEmployee> emps = m2.Employees;
            if (emps.Any(p => !p.TInfoSummaries.Any() || p.TInfoSummaries.OrderByDescending(q => q.SerialNO).FirstOrDefault().FullyFilled == false))
            {
                TempData["dmMessage"] = "还有未成功提交确认的人员，不能导出";
                return View("Index", m2);
            }
            else
            {
                string physicalRoot = HttpContext.Server.MapPath("/HRWEB");
                string physicalPath = physicalRoot + "/Templates/";
                string template = physicalPath + "科室核对打印表.xls";
                HSSFWorkbook wb = null;
                ISheet sheet1 = null;
                try
                {
                    FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                    wb = new HSSFWorkbook(fs);
                }
                catch (IOException)
                {
                    TempData["dmMessage"] = "服务器正忙，请稍后再试";
                    return View("Index", m2);
                }
                sheet1 = wb.GetSheet("sheet1");
                int i = 2;
                foreach (TEmployee emp in m2.Employees)
                {
                    IRow row = sheet1.CreateRow(i);
                    row.CreateCell(0).SetCellValue(i - 1);
                    row.CreateCell(1).SetCellValue(m2.SelectedDeptName);
                    row.CreateCell(2).SetCellValue(emp.FName);
                    row.CreateCell(3).SetCellValue(emp.FPublicID);
                    row.CreateCell(4).SetCellValue(emp.Feedback());
                
                    row.SetCellBorder();
                    row.Cells[4].CellStyle.WrapText = true;
                    //int cRow = emp.Feedback().Length / 35;
                    //row.HeightInPoints = 20;
                    i++;
                }
                IRow _row = sheet1.CreateRow(i);
            
                _row.CreateCell(4).SetCellValue("科主任/护士长签字：                   时间：");
                _row.HeightInPoints = 30;
                return File(ExcelHelper.DownLoadHelper(wb, "Export.xls"), "application/vnd.ms-excel");
                
            }
        }
        private DeptEmployeeModel BuildDeptModel(DeptEmployeeModel m)
        {
            List<TEmployee> list = new List<TEmployee>();
            //var s = from e in ent.TEmployees from d in ent.TDepts where e.FEmployeeID == d.FEmployeeID select new { Emp = e, Dept = d };
            //var s1 = s.GroupBy(p => p.Dept.FEmployeeID).OrderByDescending(p=>p.FirstOrDefault().Dept.FValidDate).Select(p=>p.FirstOrDefault());
            ////var s1 = s.OrderByDescending(p => p.Dept.FValidDate).GroupBy(p => p.Emp.FEmployeeID).Select(p => p.FirstOrDefault());
            //var s2 = s1.Where(p => p.Dept.FKQDeptCode == m.SelectedDeptCode);
            //var s3 = s2.Where(p => p.Emp.TEmployeeStatus.OrderByDescending(q => q.FValidDate).FirstOrDefault().FStatusCode == "01");
            var s = ent.TDepts.Where(p => p.FKQDeptCode == m.SelectedDeptCode);
            var s2 = s.Where(p => p.FInvalidDate == null);
            s2 = s2.Where(p => p.TEmployee.TEmployeeStatus.OrderByDescending(q => q.FOperateDate).FirstOrDefault().FStatusCode == "01");
            if (!m.DispAll)
            {
                foreach (TDept dept in s2)
                {
                    TEmployee emp = dept.TEmployee;
                    if (!emp.TInfoSummaries.Any() || emp.TInfoSummaries.OrderByDescending(p => p.SerialNO).FirstOrDefault().FullyFilled == false)
                    {
                        list.Add(emp);
                    }
                }
            }
            else
            {
                foreach (TDept dept in s2)
                {
                    TEmployee emp = dept.TEmployee;
                    list.Add(emp);
                }
            }
            
            //if (!m.DispAll)
            //{
            //    s3 = s3.Where(p => !p.Emp.TInfoSummaries.Any()||p.Emp.TInfoSummaries.OrderByDescending(q => q.SerialNO).FirstOrDefault().FullyFilled == false);
            //}
            //foreach (var a in s3)
            //{
            //    list.Add(a.Emp);
            //}
            m.Employees = list;
            return m;
        }
    }
}
